var app = getApp();
var utils = require('../../utils/shop/formatShop.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //默认头像
    groupImg:"../../images/moren.png",

    //产品详情
    productDetail: {},

    //保障条件图片
    icon_bz: "../../images/gou.png",
    seven_return: false, //7天退换
    two_day_send: false, //48小时发货
    compensate: false,   //假一赔十

    //属性弹窗
    showModalStatus: false,
    imageHeight: 0,
    imageWidth: 0,

    //购买需要传输的信息
    postData: {
      UsersID: '',      //商家ID
      User_ID: 0,       //会员ID
      OwnerID: 0,       //会员上级ID
      ProductsID: 0,    //产品ID  在 onLoad中赋值
      spec_list: '',    //选择属性id  1,2   数字从小到大
      cattsel: '',      //选择属性名称
      //atrid_str: '',    //选择属性  1；2   数字从小到大
      //atr_str: '',      //选择属性名称
      count: 0,         //选择属性的库存
      showimg: '',      //选择属性的图片(用产品图片代替)
      Qty: 1,           //购买数量
      cart_key: '',     //购物车类型   CartList（加入购物车）、DirectBuy（立即购买）、PTCartList（不能加入购物车）
      has_pintuan: 1,
      type: 'cart',

      teamid: 0
    },

    check_attr: {},    //记录选择的属性
    check_attrid_arr: [],
    submit_flag: false, //提交按钮状态

    //团详情 (只有一条数据 [0])
    teamsList: {},

    //全部产品
    allArgs: {            //全部产品接口请求数据
      act: 'get_pro',
      pintuan_flag: 1,
      page: 1,
      pageSize: 10
    },
    allProducts: [],
    allProducts_flag: true,

    //加载更多动画
    loading: true
  },

  //购买数量加号的事件
  bindPlus: function () {
    if (this.data.postData.Qty < this.data.postData.count) {
      this.setData({
        'postData.Qty': this.data.postData.Qty + 1
      })
    } else {
      wx.showToast({
        title: '购买数量不能大于库存量',
        icon: 'none',
      });
      this.setData({
        'postData.Qty': this.data.postData.count
      })
    }
  },
  //购买数量减号的事件
  bindMinus: function () {
    if (this.data.postData.Qty > 1) {
      this.setData({
        'postData.Qty': this.data.postData.Qty - 1
      });
    } else {
      wx.showToast({
        title: '购买数量不能小于1',
        icon: 'none',
      });
      this.setData({
        'postData.Qty': 1
      });
    }
  },
  //输入产品数量
  bindManual: function (e) {
    var Qty = e.detail.value;
    if (Qty < 1) {
      wx.showToast({
        title: '购买数量不能小于1',
        icon: 'none',
      });
      Qty = 1;
    } else if (Qty > this.data.postData.count) {
      wx.showToast({
        title: '购买数量不能大于库存量',
        icon: 'none',
      });
      Qty = this.data.postData.count;
    }
    this.setData({
      'postData.Qty': Qty
    });
  },

  //选择属性值事件
  selectAttrValue: function (e) {
    var value_index = e.currentTarget.dataset.valueindex; //选择的属性值索引
    var attr_index = e.currentTarget.dataset.attrindex;   //选择的属性索引
    if (this.data.check_attrid_arr.indexOf(value_index) > -1) return false;
    //记录选择的属性
    var check_attr = Object.assign(this.data.check_attr, { [attr_index]: value_index }); //记录选择的属性  attr_index外的[]必须

    //属性处理
    var check_attrid = [];
    var check_attrname = [];
    var check_attrnames = [];
    for (var i in check_attr) {
      var attr_id = check_attr[i];
      check_attrid.push(attr_id);
      check_attrname[attr_id] = i;
    }

    //数组排序  按从小到大排
    var check_attrid_arr = check_attrid;
    check_attrid = utils.number_sort(check_attrid);
    //获取对应的属性名称
    for (var i = 0; i < check_attrid.length; i++) {
      var attr_id = check_attrid[i];
      var attr_name = check_attrname[attr_id];
      check_attrnames.push(attr_name + ':' + this.data.productDetail.skujosn[attr_name][attr_id]);
    }

    //数组转化为字符串
    check_attrid = check_attrid.join(';');
    check_attrnames = check_attrnames.join(';');

    var attr_val = this.data.productDetail.skuvaljosn[check_attrid];   //选择属性对应的属性值

    //判断属性库存
    if (attr_val && attr_val.Property_count <= 0) {
      wx.showToast({
        title: '您选择的 ' + check_attrnames + ' 库存不足，请选择其他属性',
        icon: 'none'
      })
      return false;
    }

    this.setData({
      check_attr: check_attr,
      check_attrid_arr: check_attrid_arr
    });

    //属性判断
    if (attr_val) {
      this.setData({
        'postData.spec_list': attr_val.Product_Attr_ID,         //选择的属性的id组合
        'postData.cattsel': attr_val.Attr_Value,        //选择属性的名称组合
        'postData.count': attr_val.Property_count,    //选择属性的库存
        'postData.showimg': typeof attr_val.Attr_Image != 'undefined' && attr_val.Attr_Image != '' ? attr_val.Attr_Image : productDetail.Products_JSON['ImgPath'][0], // 选择属性的图片
        productDetail_price: attr_val.pt_pricex ? attr_val.pt_pricex : this.data.productDetail.pintuan_pricex, //选择属性的价格
        submit_flag: (!this.data.check_attr || Object.getOwnPropertyNames(this.data.check_attr).length != Object.getOwnPropertyNames(this.data.productDetail.skujosn).length) ? false : true
      });
    }

    //购买数量处理  大于最高时赋值最高值
    if (this.data.postData.Qty > this.data.postData.count) {
      this.setData({
        'postData.Qty': this.data.postData.count
      });
    }
  },

  /* 点击确定 */
  submit: function () {
    //判断是否能提交
    if (this.data.submit_flag) {
      //判断选择属性库存是否充足
      if (this.data.postData.Qty > this.data.postData.count) {
        wx.showToast({
          title: '购买数量大于库存数',
          icon: 'none'
        })
        return false;
      }
      //检查用户是否登录
      if (!app.globalData.userInfo) {
        app.login('', this.submit);
      } else {
        if (this.data.teamsList[0].userid == app.globalData.userInfo.User_ID) {
          this.reset_postData();
          wx.showToast({
            title: '自己不能参加自己开的团',
            icon: 'none'
          })
          return false;
        }
        if (this.data.postData.cart_key == '') {
          wx.showToast({
            title: '请选择进行的操作',
            icon: 'none'
          })
          return false;
        }
        this.setData({
          'postData.UsersID': app.globalData.userInfo.Users_ID,
          'postData.User_ID': app.globalData.userInfo.User_ID,
          'postData.OwnerID': app.globalData.userInfo.Owner_Id,
          'postData.pay_type': app.globalData.init.appid
        });
        app.http_req(this.data.postData, app.globalData.init.handle_cart_url, 'POST', this.checkout);
      }
    } else {
      wx.showToast({
        title: '请完善属性',
        icon: 'loading',
        duration: 1000
      });
    }
  },

  //初始化提交数据
  reset_postData: function () {
    this.setData({
      'postData.spec_list': '',
      'postData.cattsel': '',
      'postData.Qty': 1,
      'postData.cart_key': '',
      check_attr: {},    //记录选择的属性
      check_attrid_arr: [],
      submit_flag: false, //提交按钮状态
    });
    this.hideModal();
  },

  //添加购物车或直接购买成功跳转到checkout页面
  checkout: function (res) {
    var that = this;
    if (res.status == 1) {
      if (that.data.postData.cart_key == 'CartList') {  //加入购物车
        //购物车产品数量
        that.setData({
          cart_pro_num: res.qty
        });
        wx.showToast({
          title: '加入购物车成功',
          icon: 'success',
          duration: 1000
        });
        //提交资料初始化
        that.reset_postData();
      } else if (that.data.postData.cart_key == 'DirectBuy' || that.data.postData.cart_key == 'PTCartList') {  //直接购买、拼团购买
        wx.navigateTo({
          url: '../checkout/checkout?cart_key=' + that.data.postData.cart_key
        });
      }
    } else {
      if (that.data.postData.cart_key == 'CartList') {  //加入购物车
        wx.showModal({
          title: '提示',
          content: '加入购物车失败，是否重新提交',
          confirmText: '重新提交',
          success: function (res) {
            if (res.confirm) {
              that.submit();
            } else {
              //提交资料初始化
              that.reset_postData();
            }
          },
          fail: function () {
            //提交资料初始化
            that.reset_postData();
          }
        });
      } else {
        wx.showToast({
          icon: 'loading',
          title: '服务器忙'
        });
      }
    }
  },

  // 显示遮罩层
  showModal: function (e) {
    var cart_key = e.currentTarget.dataset.action;  //DirectBuy：立即购买   CartList：加入购物车   PTCartList：拼团购买
    if ('DirectBuy,CartList,PTCartList'.indexOf(cart_key) > -1) {
      this.setData({
        'postData.cart_key': cart_key,
        submit_flag: this.data.productDetail.skujosn ? false : true
      });
    } else {
      wx.showModal({
        title: '警告',
        content: '请勿非法操作',
        showCancel: false
      });
      return false;
    }
    var animation = wx.createAnimation({
      duration: 200,
      delay: 0
    });
    this.animation = animation;
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    });
  },
  // 隐藏遮罩层
  hideModal: function () {
    this.setData({
      'postData.cart_key': ''
    });
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "step-start",
      delay: 0
    });
    this.setData({
      animationData: animation.export(),
      showModalStatus: false
    });
  },

  //图片加载失败处理（显示默认图片）
  show_default_proImg: function (e) {
    var proid = e.currentTarget.dataset.proid;
    var cate = e.currentTarget.dataset.cate;
    if (cate == 'all') {
      this.setData({
        pintuanProducts: utils.show_default_proImg(this.data.allProducts, proid)
      });
    }
  },

  //开团人头像加载失败处理（显示默认图片）
  show_default_userImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var teamsList = this.data.teamsList;
    for (var i in teamsList[0]['teamdetail']) {
      if (index == i) {
        teamsList[0]['teamdetail'][i].user.User_HeadImg = '../../images/moren.png';
      }
    }
    this.setData({
      teamsList: teamsList
    });
  },

  //获得产品的详情
  productInfo: function (res) {
    if (res.errorCode === 0) {
      var productData = utils.formatShop(app.globalData.init.front_url, [res.data])[0];
      //设置标题
      app.setNavBarTitle(productData.Products_Name);
      // 拼团省多少
      productData['save_money'] = Math.round((productData.Products_PriceX - productData.pintuan_pricex) * 100) / 100;

      this.setData({
        productDetail: productData,
        productDetail_price: productData.pintuan_pricex,
        'postData.showimg': productData.Products_JSON['ImgPath'][0],
        'postData.count': productData.Products_Count,
        'postData.Qty': this.data.postData.Qty > productData.Products_Count ? productData.Products_Count : this.data.postData.Qty,
        submit_flag: productData.skujosn ? false : true,
      });
    } else {
      wx.showModal({
        title: '提示',
        content: typeof res.msg !== 'undefined' ? res.msg : '产品查询失败',
        showCancel: false,
        success: function () {
          wx.navigateBack({
            delta: 1
          });
        }
      })
    }
  },

  //获取团详情回调
  getTeamDetail: function (res) {
    if (res.errorCode == 0) {
      var teamsList = res.data;
      if (teamsList[0].teamstatus != 0) {
        wx.showModal({
          title: '提示',
          content: '该团状态不是拼团中，不能参团',
          showCancel: false,
          success: function () {
            wx.navigateBack({
              delta: 1
            });
          }
        });
        return false;
      }

      for (let i in teamsList) {
        let item = teamsList[i].teamdetail;
        for (let j in item) {
          item[j].user.User_HeadImg = utils.img_path(app.globalData.init.front_url, item[j].user.User_HeadImg);
        }
      }

      this.setData({
        'postData.teamid': teamsList[0].id,
        teamsList: teamsList
      });
      //倒计时
      utils.count_down(this, 0);

    } else {
      wx.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false,
        success: function () {
          wx.navigateBack({
            delta: 1
          });
        }
      })
    }
  },

  //请求全部产品
  setAllProducts: function () {
    this.setData({
      loading: true
    });
    app.http_req(this.data.allArgs, app.globalData.init.api_url, 'POST', res => {
      if (res.errorCode === 0) {
        //格式化成为前端方便展示的产品格式
        var old_allProducts = this.data.allProducts;
        var allProducts = utils.formatShop(app.globalData.init.front_url, res.data);
        this.setData({
          allProducts: old_allProducts.concat(allProducts),
          'allArgs.page': this.data.allArgs.page + 1,
          allProducts_flag: (res.totalCount / this.data.allArgs.pageSize) > this.data.allArgs.page ? true : false
        });
      } else if (res.errorCode == 0) {
        this.setData({
          allProducts: [],
          allProducts_flag: false
        });
      }

      // 结束下拉刷新
      utils.overPullDownRefresh();

      this.setData({
        loading: false
      });
    });
  },

  //跳转详情页
  detail: function (e) {
    var proid = e.currentTarget.dataset.proid;
    var ptflag = e.currentTarget.dataset.ptflag;
    wx.redirectTo({
      url: ptflag ? '../detail_pt/detail_pt?proid=' + proid : '../detail/detail?proid=' + proid
    });
  },

  //页面加载
  load: function () {
    //检查用户是否登录
    if (!app.globalData.userInfo) {
      app.login('', this.load);
      return false;
    }
    this.setData({
      'postData.User_ID': app.globalData.userInfo.User_ID
    });

    //获取产品详情
    var detailArgs = {
      Products_ID: this.data.postData.ProductsID,
      User_ID: app.globalData.userInfo.User_ID ? app.globalData.userInfo.User_ID : 0,
      act: 'detail'
    };
    app.http_req(detailArgs, app.globalData.init.product_url, 'POST', this.productInfo);

    //定义查询参团列表参数
    var ptTeamArgs = {
      act: 'get_pintuan_team_detail',
      Products_ID: this.data.postData.ProductsID,
      User_ID: app.globalData.userInfo.User_ID ? app.globalData.userInfo.User_ID : 0,
      teamid: this.data.postData.teamid
    };
    //查询参团信息
    app.http_req(ptTeamArgs, app.globalData.init.api_url, 'POST', this.getTeamDetail);

    // 初始化全部产品
    this.setAllProducts();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideLoading();
    //获取产品id
    if (options.proid && options.teamid) {
      this.setData({
        'postData.ProductsID': options.proid,
        'postData.teamid': options.teamid
      });

      //获取分享链接中携带的ownerid，用于用户注册
      if (options.ownerid) {
        app.globalData.ownerid = options.ownerid;
      }
      this.load();
    } else {
      wx.showModal({
        title: '提示',
        content: '缺少必要的参数',
        showCancel: false,
        success: function () {
          wx.navigateBack({
            delta: 1
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.reset_postData();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.allProducts_flag && !this.data.loading) {
      this.setAllProducts();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var shartData = {
      title: '参团--' + this.data.productDetail.Products_Name,
      path: '/pages/cantuan/cantuan?proid=' + this.data.productDetail.Products_ID + '&teamid=' + this.data.postData.teamid + '&ownerid=' + app.globalData.userInfo.User_ID
    };
    return app.shareInfo(shartData);
  }
})